﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebMvc.Areas.Sys.Models;
using WebMvc.Controllers;
using WebMvc.Models;

namespace WebMvc.Areas.Sys.Controllers
{
    [Area("Sys")]
    public class DepartmentController : BaseController<Department>
    {
        public DepartmentController(EFDbContext context) : base(context)
        {
        }

        /// <summary>
        /// 获取功能树JSON数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTreeData()
        {
            var entitys = GetAllListToJson();
            List<TreeModel> treeModels = new List<TreeModel>();
            foreach (var entity in entitys)
            {
                treeModels.Add(new TreeModel() { Id = entity.Id.ToString(), Text = entity.Name, Parent = entity.ParentId == 0 ? "#" : entity.ParentId.ToString() });
            }
            return Json(treeModels);
        }
        /// <summary>
        /// 获取子级功能列表
        /// </summary>
        /// <returns></returns>
        public IActionResult GetChildrenByParent(int parentId = 0, int pageIndex = 1)
        {
            var rowCount = 0;
            var totalPages = 0;
            
            var result = GetEntitysByParentId(out rowCount, out totalPages, parentId, pageIndex);

            return Json(new
            {
                rowCount = rowCount,
                pageCount = totalPages,
                rows = result,
            });
        }

        public IActionResult GetAllChildrenByParent(int parentId = 0)
        {
            var result = GetEntitysByLambdaAndSort(o=>o.ParentId==parentId,OrderLambda,true);
            return Json(result);
        }

        /// <summary>
        /// 根据父Id，返回子实体集合
        /// </summary>
        /// <param name="rowCount">总数</param>
        /// <param name="pageCount">总页数</param>
        /// <param name="parentId">父Id</param>
        /// <param name="pageIndex">当前页码</param>
        /// <returns>实体集合</returns>
        public List<Department> GetEntitysByParentId(out int rowCount, out int pageCount, int parentId, int pageIndex)
        {
            return GetPagedEntitysByLambdaAndSort(pageIndex,PageSize, out rowCount, out pageCount, o => o.ParentId == parentId, OrderLambda, IsASC).ToList();
        }

        //显示所有允许显示的部门（这里只允许显示派出所）
        [AllowAnonymous]
        public IActionResult GetAllDepIsDisplay()
        {
            var result = GetEntitysByLambdaAndSort(o => o.IsDisplay, OrderLambda, IsASC);
            return Json(result);
        }
    }
}
